<template>
  <div class="my-table">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            :icon="Plus"
            plain
            type="primary"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            :icon="Delete"
            :disabled="!multiple"
            plain
            type="danger"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            plain
            :icon="SaveIcon"
            type="danger"
            @click="handleSave"
        >保存
        </el-button>
      </el-col>
    </el-row>

    <el-table
        ref="tableRef"
        :data="tableData"
        row-key="id"
        border
        style="width: 100%; height: 300px"
        @selection-change="handleSelectionChange"
        @cell-click="handleCellClick"
        @cell-dblclick="handleCellDblClick"
        @row-contextmenu="handleRowContextmenu"
    >
      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column prop="headerName" label="标签名称" width="150">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'headerName')">
            <el-select
                v-model="scope.row.headerName"
                filterable
                clearable
                placeholder="请选择标签"
                @change="handleHeaderNameChange(scope.row, $event)"
                @blur="finishEdit(scope.row, 'headerName')"
            >
              <el-option
                  v-for="option in tagOptions"
                  :key="option.id"
                  :label="option.combinationName"
                  :value="option.id"
              />
            </el-select>
          </template>
          <template v-else>
            {{ getHeaderNameLabel(scope.row.headerName) }}
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="field" label="字段名称" width="120">
        <template #default="scope">
          {{ scope.row.field }}
        </template>
      </el-table-column>

      <el-table-column prop="editable" label="是否编辑" width="100" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'editable')">
            <el-checkbox
                v-model="scope.row.editable"
                @change="finishEdit(scope.row, 'editable')"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.editable" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="sortable" label="是否排序" width="100" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'sortable')">
            <el-checkbox
                v-model="scope.row.sortable"
                @change="finishEdit(scope.row, 'sortable')"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.sortable" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="hide" label="是否隐藏" width="100" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'hide')">
            <el-checkbox
                v-model="scope.row.hide"
                @change="finishEdit(scope.row, 'hide')"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.hide" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="filter" label="是否过滤" width="100" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'filter')">
            <el-checkbox
                v-model="scope.row.filter"
                @change="finishEdit(scope.row, 'filter')"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.filter" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="resizable" label="是否调整大小" width="120" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'resizable')">
            <el-checkbox
                v-model="scope.row.resizable"
                @change="finishEdit(scope.row, 'resizable')"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.resizable" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="checkboxSelection" label="是否设置数据复选框" width="150" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'checkboxSelection')">
            <el-checkbox
                v-model="scope.row.checkboxSelection"
                @change="finishEdit(scope.row, 'checkboxSelection')"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.checkboxSelection" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="headerCheckboxSelection" label="表头是否显示复选框" width="170" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'headerCheckboxSelection')">
            <el-checkbox
                v-model="scope.row.headerCheckboxSelection"
                @change="finishEdit(scope.row, 'headerCheckboxSelection')"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.headerCheckboxSelection" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="headerCheckboxSelectionFilteredOnly" label="是否过滤后可见行可选" width="200" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'headerCheckboxSelectionFilteredOnly')">
            <el-checkbox
                v-model="scope.row.headerCheckboxSelectionFilteredOnly"
                @change="finishEdit(scope.row, 'headerCheckboxSelectionFilteredOnly')"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.headerCheckboxSelectionFilteredOnly" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="lockPinned" label="是否冻结列" width="120" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'lockPinned')">
            <el-checkbox
                v-model="scope.row.lockPinned"
                @change="finishEdit(scope.row, 'lockPinned')"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.lockPinned" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="pinned" label="是否固定列" width="120" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'pinned')">
            <el-checkbox
                v-model="scope.row.pinned"
                @change="finishEdit(scope.row, 'pinned')"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.pinned" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="lockPosition" label="是否禁止拖动列" width="150" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'lockPosition')">
            <el-checkbox
                v-model="scope.row.lockPosition"
                @change="finishEdit(scope.row, 'lockPosition')"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.lockPosition" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="lockVisible" label="是否禁用通过菜单更改可见性" width="220" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'lockVisible')">
            <el-checkbox
                v-model="scope.row.lockVisible"
                @change="finishEdit(scope.row, 'lockVisible')"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.lockVisible" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="width" label="列宽" width="100">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'width')">
            <el-input-number
                v-model="scope.row.width"
                controls-position="right"
                :min="0"
                @change="finishEdit(scope.row, 'width')"
                @blur="finishEdit(scope.row, 'width')"
            />
          </template>
          <template v-else>
            {{ scope.row.width }}
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="maxWidth" label="最大宽度" width="100">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'maxWidth')">
            <el-input-number
                v-model="scope.row.maxWidth"
                controls-position="right"
                :min="0"
                @change="finishEdit(scope.row, 'maxWidth')"
                @blur="finishEdit(scope.row, 'maxWidth')"
            />
          </template>
          <template v-else>
            {{ scope.row.maxWidth }}
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="minWidth" label="最小宽度" width="100">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'minWidth')">
            <el-input-number
                v-model="scope.row.minWidth"
                controls-position="right"
                :min="0"
                @change="finishEdit(scope.row, 'minWidth')"
                @blur="finishEdit(scope.row, 'minWidth')"
            />
          </template>
          <template v-else>
            {{ scope.row.minWidth }}
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="cellEditor" label="单元格编辑器" width="150">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'cellEditor')">
            <el-select
                v-model="scope.row.cellEditor"
                @change="finishEdit(scope.row, 'cellEditor')"
                @blur="finishEdit(scope.row, 'cellEditor')"
            >
              <el-option label="文本编辑器" value="InputEditor" />
              <el-option label="选择框" value="AgGridSelect" />
              <el-option label="日期选择器" value="AgGridDateSelect" />
              <el-option label="数字编辑器" value="AgGridNumberInput" />
            </el-select>
          </template>
          <template v-else>
            {{ getCellEditorLabel(scope.row.cellEditor) }}
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="cellEditorParams" label="编辑框参数" width="120">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'cellEditorParams')">
            <el-input
                v-model="scope.row.cellEditorParams"
                @blur="finishEdit(scope.row, 'cellEditorParams')"
                @keyup.enter="finishEdit(scope.row, 'cellEditorParams')"
            />
          </template>
          <template v-else>
            {{ scope.row.cellEditorParams }}
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="cellStyle" label="单元格css风格" width="150">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'cellStyle')">
            <el-input
                v-model="scope.row.cellStyle"
                @blur="finishEdit(scope.row, 'cellStyle')"
                @keyup.enter="finishEdit(scope.row, 'cellStyle')"
            />
          </template>
          <template v-else>
            {{ scope.row.cellStyle }}
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="isCustomRenderer" label="是否自定义单元格渲染器" width="180" align="center">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'isCustomRenderer')">
            <el-checkbox
                v-model="scope.row.isCustomRenderer"
                @change="handleCustomRendererChange(scope.row)"
            />
          </template>
          <template v-else>
            <el-checkbox v-model="scope.row.isCustomRenderer" disabled />
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="cellRendererParams" label="自定义渲染器参数" width="150">
        <template #default="scope">
          <template v-if="isEditing(scope.row, 'cellRendererParams')">
            <el-input
                v-model="scope.row.cellRendererParams"
                @blur="finishEdit(scope.row, 'cellRendererParams')"
                @keyup.enter="finishEdit(scope.row, 'cellRendererParams')"
            />
          </template>
          <template v-else>
            {{ scope.row.cellRendererParams }}
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="cellRenderer" label="自定义渲染器组件(右键菜单设计)" width="250">
        <template #default="scope">
          <template v-if="scope.row.cellRenderer === 'WrapColumnDesignNestedDragItem'">
            <el-link @click="handleDesign(scope.row)">设计</el-link>
          </template>
          <template v-else>
            {{ scope.row.cellRenderer || '' }}
          </template>
        </template>
      </el-table-column>
    </el-table>

    <dropdown-menu
        ref="menuRef"
        v-click-outside="handleClickMenuOutside"
        :y="y"
        :x="x"
        style="position:absolute;"
        :options="menuOptions"
        @item-click="handleMenuClick"
    />

    <el-dialog
        v-model="dialogVisible"
        title="提示"
        :fullscreen="true"
    >
      <FormDesigner1
          name="UPDATE"
          :pageInfo="pageInfo"
          :isPage="false"
          @updatedesigner="updatedesigner"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Plus, Delete } from "@element-plus/icons-vue"
import { useIcon } from "@/components/common/util"
import FormDesigner1 from '@/views/modeling/form/designer.vue'
import { listCombination } from "@/api/business/extmodelfieldmetadatatag"
import { genId } from "@/components/form/designer/util/common"
import type { MenuOption } from "@/components/menu"
import DropdownMenu from "@/components/menu/DropdownMenu.vue"

const emit = defineEmits<{
  (e: 'change', newColumnsDef: object): void
}>()

const props = defineProps({
  columnDefs: {
    type: Array,
    default: () => []
  }
})

// 基本数据
const SaveIcon = useIcon('ali_save')
const tableRef = ref()
const multiple = ref(false)
const tableData = ref<any[]>([])
const tagOptions = ref<any[]>([])
const dialogVisible = ref(false)

// 编辑状态管理
const editingCell = reactive({
  rowId: '',
  field: ''
})

// 右键菜单相关
const menuRef = ref<any>()
const menuOptions = reactive<MenuOption[]>([
  { text: '设计', command: 'designer' }
])
const contextmenuRow = ref<any>()
const currentRowId = ref<any>()
const x = ref(0)
const y = ref(0)

// 页面信息
const pageInfo = ref({
  "mode": "design",
  "size": "default",
  "style": "",
  "children": [],
  "labelWidth": "120px",
  "labelPosition": "auto"
})

// 初始化数据
const initTableData = () => {
  tableData.value = JSON.parse(JSON.stringify(props.columnDefs || []))
  fillIdForRow(tableData.value)
}

// 填充ID
const fillIdForRow = (rows: any[]) => {
  for (let i = 0; i < rows.length; i++) {
    if (!rows[i].id) {
      rows[i].id = genId()
    }
  }
}

// 检查是否正在编辑指定单元格
const isEditing = (row: any, field: string) => {
  return editingCell.rowId === row.id && editingCell.field === field
}

// 获取标签名称显示文本
const getHeaderNameLabel = (value: any) => {
  if (!value) return ''
  const option = tagOptions.value.find(opt => opt.id === value)
  return option ? option.combinationName : value
}

// 获取编辑器标签
const getCellEditorLabel = (value: string) => {
  const options = [
    { label: '文本编辑器', value: 'InputEditor' },
    { label: '选择框', value: 'AgGridSelect' },
    { label: '日期选择器', value: 'AgGridDateSelect' },
    { label: '数字编辑器', value: 'AgGridNumberInput' }
  ]
  const option = options.find(opt => opt.value === value)
  return option ? option.label : value
}

// 处理单元格点击（开始编辑）
const handleCellClick = (row: any, column: any) => {
  // 设置新的编辑状态
  editingCell.rowId = row.id
  editingCell.field = column.property

  // 对于选择框，延迟获取焦点
  if (column.property === 'headerName') {
    nextTick(() => {
      const selectInput = document.querySelector('.el-table .el-select input')
      if (selectInput) {
        selectInput.focus()
      }
    })
  }
}
// 处理标签名称变化
const handleHeaderNameChange = (row: any, value: any) => {
  // 查找选中的选项
  const selectedOption = tagOptions.value.find(opt => opt.id === value)

  // 如果找到选项且有fieldEnName属性，则回填到字段名称
  if (selectedOption && selectedOption.fieldEnName) {
    row.field = selectedOption.fieldEnName
  }

  finishEdit(row, 'headerName')
}

// 完成编辑
const finishEdit = (row: any, field: string) => {
  // 保持编辑状态，允许用户继续编辑其他字段
  // 只有在切换到其他行时才清除编辑状态
}

// 处理自定义渲染器变化
const handleCustomRendererChange = (row: any) => {
  if (row.isCustomRenderer) {
    row.cellRenderer = 'WrapColumnDesignNestedDragItem'
    row.cellRendererParams = "[]"
  } else {
    row.cellRenderer = null
    row.cellRendererParams = null
  }
  finishEdit(row, 'isCustomRenderer')
}

// 双击处理
const handleCellDblClick = (row: any, column: any) => {
  if (column.property === 'cellRenderer' && row.cellRenderer === 'WrapColumnDesignNestedDragItem') {
    handleDesign(row)
  } else {
    // 双击开始编辑
    handleCellClick(row, column)
  }
}

// 处理右键菜单
const handleRowContextmenu = (row: any, column: any, event: PointerEvent) => {
  event.preventDefault()
  contextmenuRow.value = row
  currentRowId.value = row.id
  x.value = event.clientX
  y.value = event.clientY

  if (column.property === 'cellRenderer' && row.cellRenderer === 'WrapColumnDesignNestedDragItem') {
    menuRef.value?.show()
  }
}

// 处理设计按钮点击
const handleDesign = (row: any) => {
  contextmenuRow.value = row
  currentRowId.value = row.id
  if (row.cellRendererParams) {
    try {
      pageInfo.value.children = JSON.parse(row.cellRendererParams)
    } catch (e) {
      pageInfo.value.children = []
    }
  }
  dialogVisible.value = true
}

// 处理菜单点击
const handleMenuClick = (item: MenuOption) => {
  if (item.command === 'designer' && contextmenuRow.value) {
    handleDesign(contextmenuRow.value)
  }
}

// 点击菜单外部隐藏
const handleClickMenuOutside = () => {
  menuRef.value?.hide()
}

// 更新设计器
const updatedesigner = (formSchema: string) => {
  dialogVisible.value = false
  if (formSchema && contextmenuRow.value) {
    contextmenuRow.value.cellRendererParams = formSchema
    // 更新表格数据
    const rowIndex = tableData.value.findIndex((r: any) => r.id === contextmenuRow.value.id)
    if (rowIndex !== -1) {
      tableData.value[rowIndex].cellRendererParams = formSchema
    }
  }
}

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  multiple.value = selection.length >= 1
}

// 创建新行
const makeNewRow = () => {
  return {
    headerName: '',
    field: '',
    editable: false,
    cellEditor: '',
    cellEditorParams: '',
    cellStyle: '',
    isCustomRenderer: false,
    cellRendererParams: '',
    cellRenderer: null,
    sortable: false,
    resizable: true,
    hide: false,
    filter: false,
    pinned: false,
    lockPinned: false,
    lockPosition: false,
    lockVisible: false,
    width: 100,
    maxWidth: 100,
    minWidth: 100,
    headerCheckboxSelection: false,
    checkboxSelection: false,
    headerCheckboxSelectionFilteredOnly: false,
    id: genId()
  }
}

// 新增行
const handleAdd = () => {
  const newRow = makeNewRow()
  tableData.value.push(newRow)
}

// 删除行
const handleDelete = () => {
  const selection = tableRef.value?.getSelectionRows() || []
  if (selection.length > 0) {
    const idsToDelete = selection.map((row: any) => row.id)
    tableData.value = tableData.value.filter((row: any) => !idsToDelete.includes(row.id))
  }
}

// 保存
const handleSave = () => {
  emit('change', JSON.parse(JSON.stringify(tableData.value)))
}

// 生命周期钩子
onMounted(async () => {
  // 获取标签选项
  try {
    const res = await listCombination()
    tagOptions.value = res.data || []
  } catch (error) {
    console.error('获取标签选项失败:', error)
  }

  // 初始化表格数据
  initTableData()
})

// 监听props变化
import { watch } from 'vue'
watch(() => props.columnDefs, () => {
  initTableData()
}, { deep: true })
</script>

<style scoped>
.my-table {
  height: 100%;
}

.mb8 {
  margin-bottom: 8px;
}

.el-table :deep(.el-table__cell) {
  padding: 2px 0;
}

.el-table :deep(.el-input__inner),
.el-table :deep(.el-input-number) {
  height: 28px;
  line-height: 28px;
}

.el-table :deep(.el-select) {
  width: 100%;
}

.el-table :deep(.el-input-number .el-input__inner) {
  text-align: left;
}

.el-table :deep(.el-checkbox) {
  vertical-align: middle;
}
</style>
